package com.axioma.dbmaint.datalayer.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.axioma.dbmaint.datalayer.dao.ServerRepository;
import com.axioma.dbmaint.datalayer.dto.ServerDTO;
import com.axioma.dbmaint.datalayer.dto.util.DBVendor;
import com.axioma.dbmaint.datalayer.dto.util.Status;


// @Repository enables some special handling of exceptions 
@Repository
public class JDBCServerRepositoryImpl implements ServerRepository {
   
	
   // We'll use the JDBCTemplate feature to query the database
   JdbcTemplate jdbcTemplate;
   
   // This RowMapper servers to translate rows from the Servers table into a ServerDTO object 
   ServerDTORowMapper rowMapper = new ServerDTORowMapper();

   public void setDataSource(DataSource dataSource) {
      jdbcTemplate = new JdbcTemplate(dataSource);
   }

   private class ServerDTORowMapper implements RowMapper<ServerDTO> {@Override
      public ServerDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
         ServerDTO dto = new ServerDTO(rs.getString("name"), rs.getInt("port"), DBVendor.valueOf(rs.getString("dbvendor")), 
               rs.getString("masterDBName"), Status.UP, rs.getString("userid"), rs.getString("password"));
         return dto;
      }
   }
   
   /* Query our SERVERS table and return a list of ServerDTO's */
   public List<ServerDTO> getServers() {
      List<ServerDTO> servers = jdbcTemplate.query("SELECT * FROM SERVERS", rowMapper);
      for (ServerDTO serverDTO : servers) {
         serverDTO.setStatus(getServerStatus(serverDTO));
      }
      System.err.println("Need to add code to verify server status! All appear to be UP for now.");
      return servers;
   }
   
   private Status getServerStatus(ServerDTO serverDTO) {
      return Status.UP;
   }

   public ServerDTO getServer(String serverName) {
      ServerDTO server = jdbcTemplate.queryForObject("SELECT * FROM SERVERS WHERE name=?", new Object[]{serverName}, rowMapper);
      return server;
   }

   public void addServer(ServerDTO server) {
      jdbcTemplate.update("INSERT INTO SERVERS (name, port, masterDBName, dbvendor, userid, password) values (?, ?, ?, ?, ?, ?)",
            server.getServerName(), server.getPort(), server.getMasterDatabaseName(), server.getVendor().toString(),  
            server.getUser(), server.getPassword());
   }

   public void deleteServer(String serverName) {
      jdbcTemplate.update("DELETE FROM SERVERS WHERE name=?", serverName);
   }

}
